package com.wyman.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import com.wyman.beans.BeanException;
import com.wyman.beans.factory.DisposableBean;
import com.wyman.beans.factory.config.BeanDefinition;

import java.lang.reflect.Method;

/**
 * @Author 李伟民
 * @Description 销毁方法适配器
 * @DateTime 2024/12/12 21:10
 */
public class DisposableBeanAdapter implements DisposableBean {


    private final Object bean;
    private final String name;
    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition){
        this.bean = bean;
        this.name = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    //既可以是实现接口的方式 也可以是配置文件的形式 使用适配器模式 统一这两种模式
    @Override
    public void destroy() throws Exception {

        if(bean instanceof DisposableBean){
            ((DisposableBean) bean).destroy();
        }

        //防止二次销毁
        if(StrUtil.isNotEmpty(destroyMethodName)&&!(bean instanceof DisposableBean && "destroy".equals(destroyMethodName))){
           Class beanClass =  bean.getClass();
           Method destroyMethod = beanClass.getMethod(destroyMethodName);
           if(destroyMethod!=null){
               destroyMethod.invoke(bean);
           }
           else{
               throw new BeanException("Couldn't find a destroy method named '" + destroyMethodName + "' on bean with name '" + name + "'");
           }
        }
    }
}
